package admin

import (
	"encoding/json"
	"fmt"
	"ginshop02/models"
	"github.com/gin-contrib/sessions"
	"net/http"

	"github.com/gin-gonic/gin"
)

type LoginController struct {
	BaseController
}

func (con LoginController) Index(c *gin.Context) {
	c.HTML(http.StatusOK, "admin/login/login.html", gin.H{})

}
func (con LoginController) DoLogin(c *gin.Context) {
	//captchaId := c.PostForm("captchaId")
	//verifyText := c.PostForm("verifyText")
	username := c.PostForm("username")
	password := c.PostForm("password")
	//if flag := models.VerifyCaptcha(captchaId, verifyText); flag == true {
	var manager []models.Manager
	password = models.Md5(password)
	models.DB.Where("username = ? AND password = ?", username, password).Find(&manager)
	if len(manager) >= 1 {
		session := sessions.Default(c)
		managerJson, jsonErr := json.Marshal(manager)
		if jsonErr != nil {
			con.error(c, "登录失败1", "/admin/login")
			return
		}
		session.Set("userinfo", managerJson)
		err := session.Save()
		fmt.Println(err)
		if err != nil {

			con.error(c, "登录失败2", "/admin/login")
			return
		}
		con.success(c, "登录成功", "/admin")
		return
	} else {
		con.error(c, "用户名不存在", "/admin/login")
		return

	}
	//} else {
	//	con.error(c, "登录失败", "/admin/login")
	//}
}
func (con LoginController) Captcha(c *gin.Context) {
	id, b64s, err := models.MakeCaptcha()
	if err != nil {
		fmt.Println(err)
	}
	c.JSON(http.StatusOK, gin.H{
		"captchaId":    id,
		"captchaImage": b64s,
	})
}
func (con LoginController) Logout(c *gin.Context) {
	session := sessions.Default(c)
	session.Delete("userinfo")
	err := session.Save()
	if err != nil {
		con.error(c, "退出失败", "/")
	} else {
		con.success(c, "退出成功", "/admin/login")
	}
}
